package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dto.AccountDto;
import com.example.dto.MenuDto;
import com.example.dto.MsgLogDto;
import com.example.exception.MyException;
import com.example.mapper.AccountMapper;
import com.example.mapper.MenuMapper;
import com.example.mapper.MsgLogMapper;
import com.example.mapper.RoleMapper;
import com.example.service.UserService;
import com.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private MsgLogMapper msgLogMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    //    发送短信
    @Override
    public void sendMsg(String phoneCode) throws MyException {

//        校验当前用户是否已注册  没注册不能发送登录验证码
        QueryWrapper<AccountDto> qr = new QueryWrapper<>();
        qr.eq("account", phoneCode);
        Long count = accountMapper.selectCount(qr);
        if (count != 0) {
            Random random = new Random();
            StringBuffer code = new StringBuffer();
            for (int i = 0; i < 6; i++) {
                code.append(random.nextInt(10));
            }
            msgLogMapper.insert(new MsgLogDto(null, phoneCode, code.toString(), new Date()));
        } else {
            throw new MyException("您还未注册,请先注册");
        }
    }

    //    登录校验
    @Override
    public String login(AccountDto accountDto) throws MyException {
        if ("code".equals(accountDto.getLoginType())) {
            QueryWrapper<MsgLogDto> qr = new QueryWrapper<>();
            qr.eq("phone_code", accountDto.getAccount())
                    .orderByDesc("insert_date")
                    .last("limit 1");
            MsgLogDto msgLogDto = msgLogMapper.selectOne(qr);
            if (msgLogDto != null && accountDto.getMsgCode().equals(msgLogDto.getMsgCode())) {
                if (new Date().getTime() - msgLogDto.getInsertDate().getTime() < 300 * 60000) {
                    return jwtUtil.createToken(accountDto.getAccount());
                }
            }
        } else {
            QueryWrapper<AccountDto> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("password", accountDto.getPassword()).eq("account", accountDto.getAccount());
            AccountDto accountDto1 = accountMapper.selectOne(queryWrapper);


            if (accountDto1 != null) {
                if (Objects.equals(accountDto1.getStatus(), "0")){
                    throw new MyException("被封号了，请联系管理员");
                }
                return jwtUtil.createToken(accountDto.getAccount());
            }
        }

        throw new MyException("登录失败");
    }

    @Override
    public AccountDto selectInfoByAccount(String account) {
        QueryWrapper<AccountDto> qr = new QueryWrapper<>();
        qr.eq("account", account);
        AccountDto accountDto = accountMapper.selectOne(qr);
        return accountDto;
    }

    @Override
    public List<MenuDto> selectMenuByUserId(Integer id) throws MyException {
        //查询用户所有角色
        List<Integer> roleList = roleMapper.selectRoleIdByUserId(id);
        if (roleList == null || roleList.size() == 0) {
            throw new MyException("用户没有任何角色");
        }


//        分布查询
//        第一步  根据角色id查询这些角色能看到的菜单的id
        List<Integer> menuListId = menuMapper.selectMenuId(roleList);
//        第二步 根据用户能看到的菜单id去菜单表查询一级菜单的名称
        QueryWrapper<MenuDto> oneQr = new QueryWrapper<>();
        oneQr.eq("parent_id", 0).in("id", menuListId);
        List<MenuDto> menuList = menuMapper.selectList(oneQr);
//        根据一级菜单查询二级菜单
        for (int i = 0; i < menuList.size(); i++) {
            QueryWrapper<MenuDto> twoQr = new QueryWrapper<>();
            twoQr.eq("parent_id", menuList.get(i).getId()).in("id", menuListId);
            List<MenuDto> secondMenuList = menuMapper.selectList(twoQr);
            menuList.get(i).setSubMenuList(secondMenuList);
        }
//        一步到位
//       根据用户拥有的角色查可以看到的菜单
        /*        List<MenuDto> menuList = menuMapper.selectMenuByRole(roleList);*/


        if (menuList == null || menuList.size() == 0) {
            throw new MyException("用户当前拥有角色没有任何权限");
        }
        return menuList;
    }


}
